package sample;

import org.dreamwork.config.ApplicationConfigParser;
import org.dreamwork.config.ConfigParseException;
import org.dreamwork.util.StringUtil;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: seth
 * Date: 13-1-11
 * Time: 下午5:46
 */
public class Config {
    private ApplicationConfigParser parser;
    public Config (String path) throws IOException, SAXException {
        parser = new ApplicationConfigParser (new File (path));
        parser.parse ();
    }

    public String getString (String path) {
        return (String) parser.getValue (path);
    }

    public int getInteger (String path) {
        String value = getString (path);
        if (!StringUtil.isEmpty (value))
            return Integer.parseInt (value.trim ());
        throw new ConfigParseException ("Can't cast " + value + " to int!");
    }

    public static void main (String[] args) throws Exception {
        Config config = new Config ("/home/seth/temp/config.xml");
        System.out.println ("base-path = " + config.getString ("base-path"));
        System.out.println ("image = " + config.getString ("image"));
        System.out.println ("size = " + config.getInteger ("hosts.size"));
        int size = config.getInteger ("hosts.size");

        System.out.println ("ext = " + config.getString ("hosts.ext"));

        for (int i = 0; i < size; i ++) {
            String expression = String.format ("hosts.[%d].ip", i);
            System.out.printf ("%s = %s%n", expression, config.getString (expression));
        }
    }
}